﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using System.Xml;
using Microsoft.Xna.Framework.Content.Pipeline;

namespace CrateManiaPipeline
{
    /// <summary>
    /// Represents a tileset (e.g. a set of image tiles)
    /// </summary>
    public class TilesetContent
    {
        /// <summary>
        /// Tile width (in pixels)
        /// </summary>
        public int TileWidth;

        /// <summary>
        /// Tile height (in pixels)
        /// </summary>
        public int TileHeight;

        /// <summary>
        /// Tileset texture
        /// </summary>
        public ExternalReference<Texture2DContent> TilesetImage;

        /// <summary>
        /// Tiles properties (by tile ID)
        /// </summary>
        public Dictionary<int, List<KeyValuePair<string, string>>> TileProperties = new Dictionary<int, List<KeyValuePair<string, string>>>();


        public TilesetContent(XmlNode tilesetNode, ContentImporterContext context)
        {
            TileWidth = int.Parse(tilesetNode.Attributes["tilewidth"].InnerText);
            TileHeight = int.Parse(tilesetNode.Attributes["tileheight"].InnerText);

            string tilesetFile = tilesetNode["image"].Attributes["source"].InnerText;

            TilesetImage = new ExternalReference<Texture2DContent>(tilesetFile);

            //
            foreach (XmlNode tile in tilesetNode.SelectNodes(".//tile"))
            {
                int tid = int.Parse(tile.Attributes["id"].InnerText) - 1;
                List<KeyValuePair<string, string>> properties = null;
                foreach (XmlNode property in tile.SelectNodes(".//property"))
                {
                    if (properties == null)
                        properties = new List<KeyValuePair<string, string>>();
                    properties.Add(
                        new KeyValuePair<string, string>(
                            property.Attributes["name"].InnerText, 
                            property.Attributes["value"].InnerText));
                }
                // register properties
                if (properties != null)
                {
#if DEBUG
                    foreach (KeyValuePair<string, string> it in properties)
                        context.Logger.LogImportantMessage("{0}:{1}", new object[] { it.Key, it.Value });
#endif
                    TileProperties.Add(tid, properties);
                }
            }
        }
    }
}
